package cServer

import (
	"fmt"

	"github.com/gin-gonic/gin"

	"gitee.com/csingo/cComponents"
	"gitee.com/csingo/cLog"
)

var (
	version = "unknown"
)

func Routes() []*RouteItem {
	return container.routes
}

func Inject(instance any) {
	Component.Inject(instance)
	if cComponents.IsConf(instance) {
		Component.InjectConf(instance.(cComponents.ConfigInterface))
		cLog.Component.InjectConf(instance.(cComponents.ConfigInterface))
	}
}

func Load() {
	fmt.Println("version", version)
	Initialize()

	// 启动 HTTP 服务
	go startHTTP()
	// 启动 GRPC 服务
	go startGRPC()

	// server component 初始化
	Component.Load()
}

func Initialize() {
	// 依赖注入
	container.DI()

	// 初始化组件
	initComponents()

	// 初始化路由
	container.ParseRoute(route_config, []gin.HandlerFunc{}, []string{}, "")
}

func initComponents() {
	// 优先加载日志组件
	cLog.Component.Load()

	// 组件实例注入 && 组件配置注入
	container.Range(func(item any) {
		if item != nil && len(components_config.Components) > 0 {
			for _, component := range components_config.Components {
				if _, isServerComponent := component.(*ServerComponent); isServerComponent {
					continue
				}
				component.Inject(item)
				if cComponents.IsConf(item) {
					component.InjectConf(item.(cComponents.ConfigInterface))
				}
			}
		}
	})

	// 组件初始化 && 获取组件配置监听函数
	var listeners = make([]*cComponents.ConfigListener, 0)
	for _, component := range components_config.Components {
		listener := component.Listen()
		listeners = append(listeners, listener...)
		if _, isServerComponent := component.(*ServerComponent); !isServerComponent {
			component.Load()
		}
	}

	// 注入监听器
	var configComponent cComponents.ComponentInterface
	for _, listener := range listeners {
		if configComponent == nil {
			for _, component := range components_config.Components {
				if component.Inject(listener) {
					configComponent = component
				}
			}
		} else {
			configComponent.Inject(listener)
		}
	}
}

func GetVersion() string {
	return version
}
